package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.atguigu.tingshu.vo.account.AccountLockResultVo;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    @Autowired
    private RechargeInfoMapper rechargeInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int checkAndDeduct(AccountDeductVo accountDeductVo) {
        //  调用mapper 层
        int count = userAccountMapper.checkAndDeduct(accountDeductVo.getUserId(),accountDeductVo.getAmount());
        //	判断是否执行成功
        if (count == 0){
            throw new GuiguException(400, "账户余额不足！");
        }
        //	执行成功,记录账户变动信息.
        this.addUserAccountDetail(accountDeductVo.getUserId(),
                "扣减成功",
                SystemConstant.ACCOUNT_TRADE_TYPE_MINUS,
                accountDeductVo.getAmount(),
                accountDeductVo.getOrderNo()
                );
        //  返回数据
        return count;
    }

    @Override
    public IPage<UserAccountDetail> findUserConsumePage(Page<UserAccountDetail> detailPage, Long userId) {
        //  select * from user_account_detail where user_id = ? and trade_type = 1204 and is_deleted = 0 limit 10;
        LambdaQueryWrapper<UserAccountDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserAccountDetail::getUserId,userId).eq(UserAccountDetail::getTradeType,"1204");
        return userAccountDetailMapper.selectPage(detailPage,wrapper);
    }

    @Override
    public IPage<UserAccountDetail> findUserRechargePage(Page<UserAccountDetail> detailPage, Long userId) {
        //  select * from user_account_detail where user_id = ? and trade_type = 1201 and is_deleted = 0 limit 10;
        LambdaQueryWrapper<UserAccountDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserAccountDetail::getUserId,userId).eq(UserAccountDetail::getTradeType,"1201");
        return userAccountDetailMapper.selectPage(detailPage,wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rechargePaySuccess(String orderNo) {
        //  根据orderNo 查询充值记录.
        RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
        if (null == rechargeInfo || rechargeInfo.getRechargeStatus().equals(SystemConstant.ORDER_STATUS_PAID)) return;
        //  修改recharge_info 状态
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
        this.rechargeInfoMapper.updateById(rechargeInfo);
        //  修改当前用户可用金额.
        this.userAccountMapper.updateUserAccount(rechargeInfo.getUserId(),rechargeInfo.getRechargeAmount());
        //  记录当前充值记录.
        this.addUserAccountDetail(rechargeInfo.getUserId(),"充值：",SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, rechargeInfo.getRechargeAmount(),orderNo);
    }

    @Override
    public void accountUnlock(String orderNo) {
        //  防止重复扣减
        String locKey =  "unlock:"+orderNo;
        //  定义一个数据key
        String dataKey = "account:lock:" + orderNo;
        Boolean result = this.redisTemplate.opsForValue().setIfAbsent(locKey, orderNo, 10, TimeUnit.MINUTES);
        //  result = true; 执行成功，第一次解锁。false 第二次解锁
        if (!result){
            return;
        }
        //  从缓存中获取，给谁扣减金额。
        AccountLockResultVo accountLockResultVo = (AccountLockResultVo) this.redisTemplate.opsForValue().get(dataKey);
        //  判断是否为空.
        if (null == accountLockResultVo){
            log.info("从缓存中获取数据失败.{}", orderNo);
            this.redisTemplate.delete(locKey);
            return;
        }
        //  执行扣减.
        int unlock = userAccountMapper.unlock(accountLockResultVo.getUserId(),accountLockResultVo.getAmount());
        //  判断
        if (unlock == 0){
            log.info("金额失败.{}", orderNo);
            this.redisTemplate.delete(locKey);
            return;
        }
        //  记录扣减信息数据.
        this.addUserAccountDetail(accountLockResultVo.getUserId(), "解锁："+accountLockResultVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_UNLOCK, accountLockResultVo.getAmount(), orderNo);
        //  删除缓存中的扣减数据.
        this.redisTemplate.delete(dataKey);
    }

    /**
     * 扣减金额
     * @param orderNo
     */
    @Override
    public void accountMinus(String orderNo) {
        //  防止重复扣减
        String locKey =  "minus:"+orderNo;
        //  定义一个数据key
        String dataKey = "account:lock:" + orderNo;
        Boolean result = this.redisTemplate.opsForValue().setIfAbsent(locKey, orderNo, 10, TimeUnit.MINUTES);
        //  result = true; 执行成功，第一次扣减。false 第二次扣减
        if (!result){
            return;
        }
        //  从缓存中获取，给谁扣减金额。
        AccountLockResultVo accountLockResultVo = (AccountLockResultVo) this.redisTemplate.opsForValue().get(dataKey);
        //  判断是否为空.
        if (null == accountLockResultVo){
            log.info("从缓存中获取数据失败.{}", orderNo);
            this.redisTemplate.delete(locKey);
            return;
        }
        //  执行扣减.
        int minus = userAccountMapper.minus(accountLockResultVo.getUserId(),accountLockResultVo.getAmount());
        //  判断
        if (minus == 0){
            log.info("扣减失败.{}", orderNo);
            this.redisTemplate.delete(locKey);
            return;
        }
        //  记录扣减信息数据.
        this.addUserAccountDetail(accountLockResultVo.getUserId(), "扣减："+accountLockResultVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, accountLockResultVo.getAmount(), orderNo);
        //  删除缓存中的扣减数据.
        this.redisTemplate.delete(dataKey);

    }

    @Override
    public AccountLockResultVo checkAndLock(AccountLockVo accountLockVo) {
        //	userId	amount	content
        //	定义锁key
        String locKey = "checkAndLock:" + accountLockVo.getOrderNo();
        //  定义一个数据key
        String dataKey = "account:lock:" + accountLockVo.getOrderNo();
        //	防止重复消费.
        Boolean result = this.redisTemplate.opsForValue().setIfAbsent(locKey, accountLockVo.getOrderNo(), 10, TimeUnit.MINUTES);
        //  result = true; 说明执行成功，第一次检查与锁定. result = false: 说明已经执行过了.
        if (!result) {
            //  从缓存中获取数据.
            AccountLockResultVo accountLockResultVo = (AccountLockResultVo) this.redisTemplate.opsForValue().get(dataKey);
            //  判断
            if (null == accountLockResultVo) {
                log.info("从缓存中获取数据失败.{}", accountLockVo.getOrderNo());
                throw new GuiguException(ResultCodeEnum.DATA_ERROR);
            }
            //  返回正常数据.
            return accountLockResultVo;
        }
        //  检查与锁定当前可用余额；
        UserAccount userAccount = userAccountMapper.check(accountLockVo.getUserId(),accountLockVo.getAmount());
        //  判断
        if (null == userAccount){
            log.info("当前用户没有可用金额, {}", accountLockVo.getUserId());
            //  删除缓存key
            this.redisTemplate.delete(locKey);
            return null;
        }
        //  锁定账户金额：
        int lock = userAccountMapper.lock(accountLockVo.getUserId(),accountLockVo.getAmount());
        if (lock == 0){
            log.info("当前用户没有锁定成功, {}", accountLockVo.getUserId());
            //  删除缓存key
            this.redisTemplate.delete(locKey);
            return null;
        }
        //  记录明细，同时将数据保存到缓存.
        AccountLockResultVo accountLockResultVo = new AccountLockResultVo();
        accountLockResultVo.setUserId(accountLockVo.getUserId());
        accountLockResultVo.setAmount(accountLockVo.getAmount());
        accountLockResultVo.setContent(accountLockVo.getContent());
        this.redisTemplate.opsForValue().set(dataKey,accountLockResultVo,10,TimeUnit.MINUTES);
        //  调用方法记录明细.
        this.addUserAccountDetail(accountLockVo.getUserId(),"锁定："+accountLockVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_LOCK,accountLockVo.getAmount(), accountLockVo.getOrderNo());
        //  返回数据
        return accountLockResultVo;
    }

    /**
     * 记录账户明细
     * @param userId
     * @param title
     * @param tradeType
     * @param amount
     * @param orderNo
     */
    private void addUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
        //  创建对象
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        //  赋值：
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(title);
        userAccountDetail.setTradeType(tradeType);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        userAccountDetailMapper.insert(userAccountDetail);
    }

    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        //	select available_amount from user_account where user_id = ?;
        return userAccountMapper.selectOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userId).select(UserAccount::getAvailableAmount)).getAvailableAmount();
    }

    @Override
    public void initUserAccount(String userId) {
        //	user_account
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(Long.parseLong(userId));
        userAccount.setTotalAmount(new BigDecimal("10"));
        userAccount.setAvailableAmount(new BigDecimal("10"));
        userAccountMapper.insert(userAccount);
    }
}
